package com.base.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.StrutsException;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateTimeConverter extends StrutsTypeConverter {


	public Object convertFromString(Map context, String[] values, Class toClass) {
		return doConvertToDate(values[0]);
	}

	public String convertToString(Map context, Object o) {
		String result = null;
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (o instanceof Date) {
			result = format1.format(o);
		}
		return result;
	}

	private Date doConvertToDate(Object value) {
		Date result = null;
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (value instanceof String) {
			try {
				if("".equals((String)value.toString().trim())) 
					return result;
				
				if(((String)value).length()>10)
					result = format2.parse((String) value);
				else
					result = format1.parse((String) value);
			} catch (ParseException e) {
				throw new StrutsException("拦截器转换日期时间出错！", e);
			}
		}
		return result;
	}
}
